<template>
  <!-- 选择机构组件 -->
  <div>
    <el-input class="v" v-model="value"></el-input>
    <el-input
      class="l"
      :value="label"
      :placeholder="placeholder"
      :style="`width:${width}`"
      prefix-icon="el-icon-search"
      readonly
      @click.native="isCheck = true"
    ></el-input>
    <el-dialog
      class="mask-add"
      :title="title"
      :visible.sync="isCheck"
      width="20%"
      center
      :append-to-body="true"
      style="z-index:99"
    >
      <el-tree
        :data="data"
        show-checkbox
        :node-key="nodeKey"
        ref="myTree"
        :check-strictly="true"
        :highlight-current="true"
        :check-on-click-node="true"
        :accordion="true"
        :props="defaultProps"
        :default-expand-all="expandAll"
        @check-change="parentModules"
        :filter-node-method="filterNode"
        style="max-height:350px;overflow:auto"
      >
      </el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button
          class="mask-button-primary button-mini"
          type="primary"
          size="mini"
          @click="checkedNode"
          >确定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script>
export default {
  name: "treeSelect",
  model: [
    {
      prop: "value",
      event: "change"
    }
  ],
  props: {
    // 绑定的值
    value: {
      type: String,
      default: ""
    },
    // 弹窗标题
    title :{
      type: String,
      default: "机构选择"
    },
    // 树结构绑定值
    data:{
       type: [Object, Array],
       required: true
    },
    // 树结构属性配置
    defaultProps: {
      type: Object,
      default() {
        return {
          children: "children",
          label: "label"
        };
      }
    },
    // 唯一id 配置
    nodeKey: {
      type: String,
      default: "id"
    },
    width: {
      type: String,
      default: "200px"
    },
    placeholder: {
      type: String,
      default: "点击选择机构"
    },
    // 默认是否展开
    expandAll: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      isCheck: false,
      label:"",
    };
  },
  methods: {
    // 树形节点支持过滤
    filterNode(val, data) {
      if (!val) return true;
      return data.label.indexOf(val) !== -1;
    },
    //
    parentModules(data, checkbox) {
      if (checkbox) {
        this.$refs.myTree.setCheckedNodes([]);
        this.$refs.myTree.setCheckedKeys([data[this.nodeKey]]);
      }
    },
    checkedNode(){
      let node = this.$refs.myTree.getCheckedNodes();
      if(node.length==0){this.value = "";this.label = ""}
      else { 
        console.log(node[0])
        this.value = node[0][this.nodeKey]
        this.label = node[0][this.defaultProps.label]
       }
       this.isCheck = false
    }
    // 回显（未完成）
  }
};
</script>
<style scoped>
.v {
  display: none;
}
.l {
  cursor: pointer;
}
</style>
